package com.luhuiguo.cms.server.web;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.luhuiguo.cms.server.service.CmsService;
import com.luhuiguo.cms.server.util.PathUtils;
import com.luhuiguo.cms.shared.model.ArticleModel;
import com.luhuiguo.cms.shared.model.ChannelModel;

@Controller
public class SiteController {

    @Autowired
    private CmsService cmsService;

    @RequestMapping("/**/c-{id}.html")
    public String channelHandler(@PathVariable("id") Long id) {

        ChannelModel channel = cmsService.getChannel(id);
        String path = channel.getPath();

        return "redirect:" + path + "index.html";
    }

    @RequestMapping("/**/index.html")
    public ModelAndView channelPathHandler(HttpServletRequest request) {

        String uri = request.getRequestURI();
        String viewName = PathUtils.getChannelViewName(uri);
        String path = PathUtils.getChannelPath(uri);
        ModelAndView mav = new ModelAndView(viewName);
        ChannelModel channel = cmsService.getChannelByPath(path);
        mav.addObject("channel", channel);
        return mav;
    }

    @RequestMapping("/**/index-{pageIndex}.html")
    public ModelAndView channelPathHandler(HttpServletRequest request, @PathVariable("pageIndex") int pageIndex) {

        String uri = request.getRequestURI();
        String viewName = PathUtils.getChannelViewName(uri);
        String path = PathUtils.getChannelPath(uri);

        ModelAndView mav = new ModelAndView(viewName);
        ChannelModel channel = cmsService.getChannelByPath(path);
        mav.addObject("channel", channel);
        mav.addObject("pageIndex", pageIndex);
        return mav;
    }

    @RequestMapping("/**/a-{id}.html")
    public ModelAndView articleHandler(HttpServletRequest request, @PathVariable("id") Long id) {

        String uri = request.getRequestURI();
        String viewName = PathUtils.getArticleViewName(uri);
        ModelAndView mav = new ModelAndView(viewName);

        ArticleModel article = cmsService.getArticle(id);
        mav.addObject("article", article);
        ChannelModel channel = cmsService.getChannel(article.getChannelId());
        mav.addObject("channel", channel);
        return mav;
    }

}
